package com.yaolong.api.configuration;
import com.yaolong.api.configuration.properties.MybatisPlusMapperRefreshProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * @author yaolong
 * @version V1.0.0
 * @program opms
 * @description mapper 热更新配置
 * @create 2023-01-30 11:04
 **/
@Slf4j
@Configuration
@EnableConfigurationProperties(MybatisPlusMapperRefreshProperties.class)
@ConditionalOnProperty(prefix = "mybatis-refresh", name = "enabled", havingValue = "true")
public class MybatisMapperHotRefreshConfiguration {
    private final MybatisPlusMapperRefreshProperties mybatisPlusMapperRefreshProperties;
    private final ResourceLoader resourceLoader;

    public MybatisMapperHotRefreshConfiguration(MybatisPlusMapperRefreshProperties mybatisPlusMapperRefreshProperties,ResourceLoader resourceLoader) {
        this.mybatisPlusMapperRefreshProperties = mybatisPlusMapperRefreshProperties;
        this.resourceLoader = resourceLoader;
    }

    @SneakyThrows
    @Bean
    public HotRefresh myDateFormatter(SqlSessionFactory sqlSessionFactory) {
        String watchDir = mybatisPlusMapperRefreshProperties.getWatchDir();
        Boolean enabled = mybatisPlusMapperRefreshProperties.getEnabled();
        if (null == enabled || !enabled) {
            log.warn("============================ mybatis-refresh not active ====================");
            return null;
        }
        if (null == watchDir) {
            log.error("请指定监控目录。");
            return null;
        }
        Path path = Paths.get(watchDir);
        if (!path.toFile().exists()) {
            log.error("监控目录不存在，请指定监控目录。");
            return null;
        }
        if (!path.toFile().isDirectory()) {
            log.error("监控路径非目录，请指定监控目录。");
            return null;
        }
        return new HotRefresh(sqlSessionFactory, path);

    }
}
